package com.yc.game.controller;

import com.yc.game.common.Const;
import com.yc.game.common.ServerResponse;
import com.yc.game.pojo.User;
import com.yc.game.service.MoneyService;
import com.yc.game.service.TrainingContentService;
import com.yc.game.service.TrainingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class TrainingController {
    @Autowired
    private TrainingContentService trainingContentService;
    @Autowired
    private TrainingService trainingService;
    @Autowired
    private MoneyService moneyService;

    /**
     * 预约代练
     */
    @RequestMapping("training/bookTraining")
    @ResponseBody
    public ServerResponse bookTraining(HttpServletRequest request,
                                       @RequestParam("trainingId") Integer trainingId) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("操作失败，请先登录");
        }
        // 查询是否已经预定过
        int result = trainingService.getByEmailAndTrainingId(user.getEmail(), trainingId);
        if (result > 0) {
            return ServerResponse.createByErrorMessage("预定失败，不能重复预定");
        }
        // 判断保证金是否充足
        boolean moneyResult = moneyService.getByEmail(user.getEmail(), trainingId);
        if (!moneyResult) {
            return ServerResponse.createByErrorMessage("保证金不足，请联系管理员增加保障金额");
        }
        // 减少金额
        moneyService.subMoneyByEmail(user.getEmail(), trainingId);
        // 写入数据库
        int count = trainingService.addTraining(user.getEmail(), trainingId);
        if (count > 0) {
            // 修改状态
            trainingContentService.updateStatus(trainingId);
            return ServerResponse.createBySuccessMessage("预订成功，等待管理员审核");
        }
        return ServerResponse.createByErrorMessage("操作失败");

    }
}

